import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart';
import '../models/member.dart';
import '../services/database_service.dart';

class MemberProvider with ChangeNotifier {
  final DatabaseService _db = DatabaseService();
  List<Member> _members = [];
  bool _isLoading = false;
  Future<List<Member>>? _loadMembersFuture;

  List<Member> get members => _members;
  bool get isLoading => _isLoading;

  Future<List<Member>> loadMembers() {
    if (_loadMembersFuture != null) {
      return _loadMembersFuture!;
    }

    _loadMembersFuture = _db.getAllMembers().then((loadedMembers) {
      _members = loadedMembers;
      _isLoading = false;
      notifyListeners();
      _loadMembersFuture = null;
      return loadedMembers;
    }).catchError((error) {
      print('Error loading members: $error');
      _isLoading = false;
      _loadMembersFuture = null;
      return <Member>[];
    });

    return _loadMembersFuture!;
  }

  Future<void> addMember(String name, String email, MemberRole role) async {
    try {
      final member = Member(
        id: const Uuid().v4(),
        name: name,
        email: email,
        role: role,
      );

      await _db.insertMember(member);
      await loadMembers(); // 重新加载以确保数据同步
    } catch (e) {
      print('Error adding member: $e');
      rethrow;
    }
  }

  Future<void> updateMember(Member member) async {
    try {
      await _db.updateMember(member);
      await loadMembers(); // 重新加载以确保数据同步
    } catch (e) {
      print('Error updating member: $e');
      rethrow;
    }
  }

  Future<void> deleteMember(String id) async {
    try {
      await _db.deleteMember(id);
      await loadMembers();
    } catch (e) {
      print('Error deleting member: $e');
      rethrow;
    }
  }

  Future<Member?> getMember(String id) async {
    try {
      return await _db.getMember(id);
    } catch (e) {
      print('Error getting member: $e');
      return null;
    }
  }

  Future<Member?> getMemberByEmail(String email) async {
    try {
      final db = await _db.database;
      final List<Map<String, dynamic>> maps = await db.query(
        'members',
        where: 'email = ?',
        whereArgs: [email],
        limit: 1,
      );

      if (maps.isEmpty) return null;
      return Member.fromMap(maps.first);
    } catch (e) {
      debugPrint('Error getting member by email: $e');
      return null;
    }
  }

  Member? getMemberById(String id) {
    try {
      return _members.firstWhere((member) => member.id == id);
    } catch (e) {
      return null;
    }
  }

  Future<List<Member>> getMembers() async {
    if (_members.isEmpty) {
      await loadMembers();
    }
    return _members;
  }

  Future<Member?> getMemberByName(String name) async {
    try {
      final db = await _db.database;
      final List<Map<String, dynamic>> maps = await db.query(
        'members',
        where: 'name = ?',
        whereArgs: [name],
        limit: 1,
      );

      if (maps.isEmpty) return null;
      return Member.fromMap(maps.first);
    } catch (e) {
      debugPrint('Error getting member by name: $e');
      return null;
    }
  }
} 